$(document).ready(function(){
	 //加载属性菜单方法
	 $('#menutreeGrid').treegrid({
		    loadMsg:"数据加载中.....",
			title: "商品分类",
			toolbar:"#menu_safe",
			singleSelect:true, 
		    fitColumns: true, //自动调整各列，用了这个属性，下面各列的宽度值就只是一个比例。  
		    striped: true, //奇偶行颜色不同  
		    remoteSort: true, //服务器端排序  
		    rownumbers:true, //显示行号  
			idField:'id',
			treeField:'name',
		    columns:[[
					{field:'id',   	title:'菜单标识',	width:70,	align:'center',hidden:true},
					{field:'name',	title:'分类名称',	width:100,	align:'left',
						formatter: function (value, row, index) {
	                        return "<input name='input_menu_name' type='checkbox' onclick=show('" + row.id + "') id='check_" + row.id + "'/>"+row.name;
	                    }},
					{field:'parentCategoryId',	title:'菜单类型',	width:70,	align:'center',
						formatter: function(value,row,index){
							if(value==0){
								return '主菜单';
							}else if(value != null){
								return '子菜单';
							}
						}}
	//						{field:'menuorder',	title:'菜单排序',	width:70,	align:'center'}
				
		    ]]
	 });
	 queryMenu();

});

/**
 * 选中父节点同时选中所有子节点
 * @param checkid
 */
function show(checkid) {
    var s = '#check_' + checkid;
    /*选子节点*/
    var nodes = $("#menutreeGrid").treegrid("getChildren", checkid);
    for (var i = 0; i < nodes.length; i++) {
        $(('#check_' + nodes[i].id))[0].checked = $(s)[0].checked;
    }
    //选上级节点
    if (!$(s)[0].checked) {
        var parent = $("#menutreeGrid").treegrid("getParent", checkid);
        while (parent) {
            parent = $("#menutreeGrid").treegrid("getParent", parent.id);
        }
    } else {
        var parent = $("#menutreeGrid").treegrid("getParent", checkid);
        var flag = true;
        var sons = parent.sondata.split(',');
        for (var j = 0; j < sons.length; j++) {
            if (!$(('#check_' + sons[j]))[0].checked) {
                flag = false;
                break;
            }
        }
        if (flag)
            $(('#check_' + parent.id))[0].checked = true;
        while (flag) {
            parent = $("#menutreeGrid").treegrid("getParent", parent.id);
            if (parent) {
                sons = parent.sondata.split(',');
                for (j = 0; j < sons.length; j++) {
                    if (!$(('#check_' + sons[j]))[0].checked) {
                        flag = false;
                        break;
                    }
                }
            }
            if (flag)
                $(('#check_' + parent.id))[0].checked = true;
        }
    }
}

/**
 * 查询菜单列表
 */
function queryMenu(){
	
	$.ajax({
		type : "post",
		url : path+"/item/v1/cat/alllist",
//		contentType : "application/json; charset=utf-8",
//		data :'{"menuname":""}',
		datatype : "json",
		success : function(data) {
			$('#menutreeGrid').treegrid('loadData',data.catlists);
		}
	});
	
}

/**
 * 查询父级菜单（新增时下拉框）
 * @param html
 * @param groupName
 */
function selectList(html,groupName){
	$.ajax({
        type: "post",
        url: path+'/item/v1/cat/list',
//      contentType : "application/json; charset=utf-8",
//		data :'{"parent":""}',
		datatype : "json",
        success: function(data){
        	$('#'+html).combobox('loadData',data);
        }
    }); 
}

/**
 * 打开新增菜单窗口
 */
function InsertMenu(){
   $("#edit_extend").empty();
   $('#menuDialog').dialog('close');
	 $('#menuDialog').dialog({
		    width: 449,
			closed: false,
		    cache: false,
		    modal: true,
		    iconCls:'icon-add'
	 });
			$('#menuid').val("");
			$('#menu_name').val("");
			$('#menuparent').combobox('setValue','');
			selectList('menuparent','');	
}

/**
 * 打开修改菜单窗口
 */
function updateMenu(){
	$("#edit_extend").empty();
	$('#menuid').val("");
	$('#menu_name').val("");
	$('#menuparent').combobox('setValue','');
	var rows =  $('#menutreeGrid').treegrid('getChecked');
	 if(rows.length == 1){
		 $('#menuDialog').dialog({
			    width: 449,
				height: 460,
				closed: false,
			    cache: false,
			    modal: true,
			    iiconCls:'icon-edit'
		 });
		var row =  rows[0];
		 setFormVal(row);
		 selectList('menuparent','');
		 var html = $('<div style="width:416px;margin-left:10px;text-align:right;margin-top:30px;"></div>');
		 $(html).append('<input name="" type="button" class="scbtn" onclick="associatedBrand('+row.id+','+row.parentCategoryId+')"    style="margin-left:15px;" value="关联品牌"/>');
		 $(html).append('<input name="" type="button" class="scbtn" onclick="addExpandAttribute('+row.id+','+row.parentCategoryId+')" style="margin-left:15px;" value="添加扩展属性"/>');
		 $(html).append('<input name="" type="button" class="scbtn" onclick="addFormatAttribute('+row.id+','+row.parentCategoryId+')" style="margin-left:15px;" value="添加规格属性"/>');
		 $('#edit_extend').append(html);
	 }else{
		 $.messager.alert("提示","请选择一条记录！");
	 }
}
	
/**
 * 新增修改菜单保存，点击保存按钮触发
 */	
function saveMenu(){
	var id =  $.trim($('#menuid').val());
	var menufile =  $.trim($('#menu_file').val());
	var menuimage =  $.trim($('#menu_image').val());
	var menuname =  $.trim($('#menu_name').val());
	var menuparent =  $.trim($('#menuparent').combobox('getValue'));
	console.log("menufile===="+menufile);
	console.log("menuimage===="+menuimage);
    //异步获取数据到javascript对象，入参为查询条件和页码信息  
	if(id != null && id !=""){
		 $.ajax({
		    	type : "post",
				url : path+'/item/v1/cat/updatecat',
				contentType : "application/json; charset=utf-8",
				datatype : "json",
				data :'{"name":"'+menuname+'","id":"'+id+'","parentCategoryId":"'+menuparent+'","specification":"'+menufile+'","defaultIcon":"'+menuimage+'"}',
		        success: function(data){
		        	if(data.result == 1){
		        		$.messager.alert("提示","修改操作成功！");
		        		$('#menuDialog').dialog('close');
		        		queryMenu();
		        	}else{
		        		$.messager.alert("提示","系统异常，请联系管理员！");
		        	}
		        }
		    });
	}else{
		 $.ajax({
		    	type : "post",
				url : path+'/item/v1/cat/insertcat',
				contentType : "application/json; charset=utf-8",
				datatype : "json",
				data :'{"name":"'+menuname+'","id":"'+id+'","parentCategoryId":"'+menuparent+'","specification":"'+menufile+'","defaultIcon":"'+menuimage+'"}',
		        success: function(data){
		        	if(data.result == 1){
		        		$.messager.alert("提示","新增操作成功！");
		        		$('#menuDialog').dialog('close');
		        		queryMenu();
		        	}else{
		        		$.messager.alert("提示","系统异常，请联系管理员！");
		        	}
		        }
		    });
	}
   
}

/**
 * 删除菜单
 */
function deleteMenu(){
	 var id= ""; 
	 $("input[name=input_menu_name]:checked").each(function(){
	        var idList = $(this).attr("id");
	        if(idList.indexOf("check_")>-1)
	            id += idList.replace("check_",'')+',';
	     });
	 if(id.length >=1){
		 $.messager.confirm('确认','确认要删除吗？',function(r) {
					if (r) {
						$.ajax({
							type: "post",
						    url: path+'/item/v1/cat/deletecat',
						    contentType : "application/json; charset=utf-8",
							datatype : "json",
						    data:id,
						    success: function(data){
						    	if(data.result == 1){
						    		$.messager.alert("提示","操作成功！");
						    		queryMenu();
						    	}else{
						    		$.messager.alert("提示","系统异常，请联系管理员！");
						    	}
						    }
				           });
					    }
				    });
	 }else{
		 $.messager.alert("提示","请先选中一行！"); 
	 }
}

/**
 * 修改时把表格中选中数据带到弹窗中
 * @param row
 */
function setFormVal(row){
	if(row.id!=null&&row.id!=""){
		$('#menuid').val(row.id);
	}
	if(row.name!=null&&row.name!=""){
		$('#menu_name').val(row.name);
	}
	if(row.parentCategoryId!=null&&row.parentCategoryId!=""){
		$('#menuparent').combobox('setValue',row.parentCategoryId);
	}
}

/**
 * 弹出关联品牌窗口
 */
function associatedBrand(categoryId,parentCategoryId){
	$("#brandList").empty();
	$('#attribute_categoryId').val(categoryId);
	selectItemBrandCheckedList(categoryId);
	$('#brandDialog').dialog({
		closed: false,
		cache: false,
		modal: true
	});
}

/**
 * 查询商品品牌
 */
/*function selectItemBrandList(){
	$.ajax({
		type: "post",
	    url: path+'/item/v1/selectitembrand?page=1&rows=10000',
	    contentType : "application/json; charset=utf-8",
		datatype : "json",
	    data:'{}',
	    success: function(data){
	    	if(data.result == 1){
	    		for(var i in data.rows){
	    		    $('#brandList').append('<label><input name="brand_to_bind" id="'+data.rows[i].id+'" type="checkbox" value="'+data.rows[i].id+'"/>'+data.rows[i].brandName+' </label>');
	    		}
	    	}else{
	    		$.messager.alert("提示","系统异常，请联系管理员！");
	    	}
	    }
    });
}*/

/**
 * 查询商品品牌[包括已选中]
 */
function selectItemBrandCheckedList(categoryId){
	var params = {
			 categoryId:categoryId
		};
	$.ajax({
		type: "post",
		url: path+'/item/v1/selectitembrandchecked',
		contentType : "application/json; charset=utf-8",
		datatype : "json",
		data:JSON.stringify(params),
		success: function(data){
			if(data.result == 1){
				for(var i in data.list){
					if(data.list[i].checked == '1'){
						$('#brandList').append('<label><input name="brand_to_bind" id="'+data.list[i].id+'" type="checkbox" checked="checked" value="'+data.list[i].id+'"/>'+data.list[i].brandName+' </label>');
					}else{
						$('#brandList').append('<label><input name="brand_to_bind" id="'+data.list[i].id+'" type="checkbox" value="'+data.list[i].id+'"/>'+data.list[i].brandName+' </label>');
					}
				}
			}else{
				$.messager.alert("提示","系统异常，请联系管理员！");
			}
		}
	});
}

/**
 * 保存类别品牌绑定
 */
function saveBrandBind(){
	var attribute_categoryId = parseInt($.trim($('#attribute_categoryId').val()));
	 var ids = new Array();
	 $("input[name='brand_to_bind']:checked").each(function(){
         var idList = parseInt($(this).attr("id"));
         ids.push(idList);
	 });
	 var params = {
			 brandIds:ids,
			 categoryId:attribute_categoryId
		};
	 if(ids.length >=1){
		$.ajax({
			type: "post",
		    url: path+'/item/v1/cat/bindcatbrand',
		    contentType : "application/json; charset=utf-8",
			datatype : "json",
		    data:JSON.stringify(params),
		    success: function(data){
		    	if(data.result == 1){
		    		$.messager.alert("提示","操作成功！");
		    	}else{
		    		$.messager.alert("提示","系统异常，请联系管理员！");
		    	}
		    }
	    });
	 }else{
		 $.messager.alert("提示","请先选中要绑定品牌！"); 
	 }
}

/**
 * 弹出扩展属性窗口
 */
function addExpandAttribute(categoryId,parentCategoryId){
	if(parentCategoryId == 0){
		$.messager.alert("提示","必须是二级分类！");
	}else{
		var usageMode = 0;     //属性类型：0-扩展属性；2-规格属性
		loadAttributeList(categoryId,usageMode);
		selectAttribute(categoryId,usageMode);
		$('#attributeListDialog').dialog({
			closed: false,
			cache: false,
			modal: true
		});
	}
}

/**
 * 弹出规格属性窗口
 */
function addFormatAttribute(categoryId,parentCategoryId){
	if(parentCategoryId == 0){
		$.messager.alert("提示","必须是二级分类！");
	}else{
		var usageMode = 2;     //属性类型：0-扩展属性；2-规格属性
		loadAttributeList(categoryId,usageMode);
		selectAttribute(categoryId,usageMode);
		$('#attributeListDialog').dialog({
			closed: false,
		    cache: false,
		    modal: true
		});
	}
}

/**
 * 加载属性列表
 */
function loadAttributeList(categoryId,usageMode){
	$('#attribute_datagrid').datagrid({
		loadMsg : "数据加载中",
//		title:"属性列表",
		border:false,
		fit : true,
		fitColumns : true,
		pagination : true,
		rownumbers : true,
		nowrap : false,
		singleSelect : true,
		onClickRow: onClickRow, 
		onAfterEdit: function (rowIndex, rowData, changes) {
//          console.info(rowData);
            $.ajax({
            	type : "post",
        		url : path+'/item/v1/param/updateattr',
        		contentType : "application/json; charset=utf-8",
        		datatype : "json",
        		data :'{"attributeName":"'+rowData.attributeName+'","id":'+rowData.id+'}',
                success: function(data){
                	if(data.result == 1){
//                		$.messager.alert("提示","修改属性列成功！");
//                		selectAttribute(categoryId,usageMode);
                	}else{
                		$.messager.alert("提示","系统异常，请联系管理员！");
                	}
                }
            });
//            editRow = undefined;
        },
		columns : [ [
//		    {field:	 'checked',checkbox:true},
		    {field : 'id',title : 'ID',	width : 100,align : 'center',hidden : true},
			{field : 'attributeName',	title : '属性名称',	width : 200,align : 'center',
				formatter: function(value,row,index){
					return 	value;
				},
				editor:{
					type:'textbox'
				}
			},
			{field : 'attributeValues',	title : '属性值',		width : 500,align : 'center',
				formatter: function(value,row,index){
					if(value != null && value != ''){
						var info='';
						for(var i in value){
							var tmp = '<span style="color:black;margin-right:10px;">'+value[i].valueStr+'<a href="#" class="easyui-linkbutton" iconCls="icon-search" style="color:blue;margin-left:3px;" onClick="deleteAttrValue('+categoryId+','+usageMode+','+value[i].id+')">删除</a></span>';
							info+= tmp;
					    }
						return info;
					}
				}
			},
			{field : 'cz',title : '操作',	width : 200,align : 'center',hidden : false,
				formatter: function(value,row,index){
				    return '<a href="#" style="color:blue;margin-left:3px;" onClick="addAttrValue('+categoryId+','+usageMode+','+row.id+')">添加属性值 </a><a href="#" style="color:blue;margin-left:3px;" onClick="deleteAttr('+categoryId+','+usageMode+','+row.id+')">删除</a>';;
				}
			}
		] ],
		toolbar : [ {
			text : '添加属性',
			iconCls : 'icon-add',
			handler : function() {
				addAttr(categoryId,usageMode);
			}
		}
//		,  {
//			text : '删除',
//			iconCls : 'icon-cancel',
//			handler : function() {
//				deleteAttr(categoryId,usageMode);
//			}		
//		}, 
		]
	});
}

var editIndex = undefined;
function endEditing(){
	if (editIndex == undefined){return true;}
	if ($('#attribute_datagrid').datagrid('validateRow', editIndex)){
		$('#attribute_datagrid').datagrid('endEdit', editIndex);
		editIndex = undefined;
		return true;
	} else {
		return false;
	}
}

/**
 * 点击行进行行编辑操作
 * @param index
 */
function onClickRow(index){
	if (editIndex != index){
		if (endEditing()){
			$('#attribute_datagrid').datagrid('selectRow', index).datagrid('beginEdit', index);
			editIndex = index;
		} else {
			$('#attribute_datagrid').datagrid('selectRow', editIndex);
		}
	}
}

/**
 * 查询属性列表（带分页）
 * @param categoryId
 * @param usageMode
 */
function selectAttribute(categoryId,usageMode){
	var params = {
			categoryId : categoryId,
			usageMode : usageMode
		};
	$("#attribute_datagrid").datagrid_pagination($("#attribute_datagrid"),path+"/item/v1/param/selectattr",params,"","");
}

/**
 * 添加属性列
 * @param categoryId
 * @param usageMode
 */
function addAttr(categoryId,usageMode){
	$('#attribute_name').val('');
	$('#attribute_value').val('');
	$('#attribute_categoryId').val(categoryId);
	$('#attribute_usageMode').val(usageMode);
	$('#attributeDialog').dialog({
	    width: 449,
		closed: false,
	    cache: false,
	    modal: true,
	    iconCls:'icon-add'
 });
}

/**
 * 删除属性列
 * @param categoryId
 * @param usageMode
 */
function deleteAttr(attribute_categoryId,attribute_usageMode,id){
	$.ajax({
    	type : "post",
		url : path+'/item/v1/param/deleteattr',
		contentType : "application/json; charset=utf-8",
		datatype : "json",
		data :id+"",
        success: function(data){
        	if(data.result == 1){
        		$.messager.alert("提示","删除属性列成功！");
        		selectAttribute(attribute_categoryId,attribute_usageMode);
        	}else{
        		$.messager.alert("提示","系统异常，请联系管理员！");
        	}
        }
    });
}

/**
 * 添加属性值
 * @param attributeId
 */
function addAttrValue(categoryId,usageMode,attributeId){
	$('#attributeValue_value').val('');
	$('#attribute_categoryId').val(categoryId);
	$('#attribute_usageMode').val(usageMode);
	$('#attribute_id').val(attributeId);
	$('#attributeValueDialog').dialog({
		width: 449,
		closed: false,
		cache: false,
		modal: true,
		iconCls:'icon-add'
	});
}

/**
 * 删除属性值
 * @param attribute_categoryId,attribute_usageMode,id
 */
function deleteAttrValue(attribute_categoryId,attribute_usageMode,id){
	$.ajax({
    	type : "post",
		url : path+'/item/v1/param/deleteattrvalue',
		contentType : "application/json; charset=utf-8",
		datatype : "json",
		data :id+"",
        success: function(data){
        	if(data.result == 1){
        		$.messager.alert("提示","删除属性值成功！");
        		selectAttribute(attribute_categoryId,attribute_usageMode);
        	}else{
        		$.messager.alert("提示","系统异常，请联系管理员！");
        	}
        }
    });
}

/**
 * 保存属性
 */
function saveAttribute(){
	var attribute_name =  $.trim($('#attribute_name').val());
	var attribute_value =  $.trim($('#attribute_value').val());
	var attribute_categoryId =  $.trim($('#attribute_categoryId').val());
	var attribute_usageMode =  $.trim($('#attribute_usageMode').val());
	$.ajax({
    	type : "post",
		url : path+'/item/v1/param/insertattr',
		contentType : "application/json; charset=utf-8",
		datatype : "json",
		data :'{"attributeName":"'+attribute_name+'","valueStr":"'+attribute_value+'","categoryId":'+attribute_categoryId+',"usageMode":'+attribute_usageMode+'}',
        success: function(data){
        	if(data.result == 1){
        		$.messager.alert("提示","新增操作成功！");
        		$('#attributeDialog').dialog('close');
        		selectAttribute(attribute_categoryId,attribute_usageMode);
        	}else{
        		$.messager.alert("提示","系统异常，请联系管理员！");
        	}
        }
    });
}

/**
 * 保存属性值
 */
function saveAttributeValue(){
	console.log("attribute_categoryId"+$.trim($('#attribute_categoryId').val()));
	var attribute_categoryId =  $.trim($('#attribute_categoryId').val());
	var attribute_usageMode =  $.trim($('#attribute_usageMode').val());
	var attribute_id =  $.trim($('#attribute_id').val());
	var attributeValue_value =  $.trim($('#attributeValue_value').val());
	$.ajax({
		type : "post",
		url : path+'/item/v1/param/insertattrvalue',
		contentType : "application/json; charset=utf-8",
		datatype : "json",
		data :'{"id":"'+attribute_id+'","valueStr":"'+attributeValue_value+'"}',
		success: function(data){
			if(data.result == 1){
				$.messager.alert("提示","新增操作成功！");
				$('#attributeValueDialog').dialog('close');
				selectAttribute(attribute_categoryId,attribute_usageMode);
			}else{
				$.messager.alert("提示","系统异常，请联系管理员！");
			}
		}
	});
}

/**
 * 上传文件方法
 */
function upload(){
	$.ajaxFileUpload({
		url:path+'/uploadcatggs',
		secureuri:false,
		fileElementId:'file_cat_ggs',
		dataType:'text',
		success:function(data){
			if(data!=null){
				var url = data.substring(data.indexOf('"url":"')+7,data.lastIndexOf('"}</pre>'));
				$.messager.alert("提示","上传成功！");
				console.log("上传规格书路径！"+url);
				$('#menu_file').val(url);
//				$("#itemAddForm [name=specification]").val(url);
			}
		},
		error:function(data){
			console.log("上传失败！");
		}
	});
}

/**
 * 上传图片方法
 */
function uploadPic(){
	$.ajaxFileUpload({
		url:path+'/uploadcatpic',
		secureuri:false,
		fileElementId:'file_fltb',
		dataType:'text',
		success:function(data){
			if(data!=null){
				var url = data.substring(data.indexOf('"url":"')+7,data.lastIndexOf('"}</pre>'));
				$.messager.alert("提示","上传成功！");
				console.log("上传分类图片路径！"+url);
				$('#menu_image').val(url);
//				$("#itemAddForm [name=specification]").val(url);
			}
		},
		error:function(data){
			console.log("上传失败！");
		}
	});
}